// pages/addMeeting/addMeeting.js
import WxValidate from '../../tools/WxValidate'
var fileID = '';

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var day1 = day + 1;
var day2 = day1 + 1;
var currentDate = year + '-' + month + '-' + day;
var tomorrow = year + '-' + month + '-' + day1;
var dayOfTomorrow = year + '-' + month + '-' + day2;

Page({

  /**
   * 页面的初始数据
   */

  data: {

    array: ['信息工程学院', '公路学院', '建工学院', '经管学院', '公用'],
    index: 0,
    allValue: {},
    tempFilePaths: '',
    roomFilePaths: './../../images/upfile.png',
    roomId: '',

    mapName: '',
    mapAddress: '',
    mapLatitude: '',
    mapLongitude: '',

    dayBarOne: '',
    dayBarTwo: '',
    dayBarThree: '',
    dayFlag: '0',
    dayOne: null,
    dayTwo: null,
    dayThree: null,

    form: {
      name: '',
      address: '',
      state: '',
      containNum: '',
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //初始化检查表单控件
    this.initValidate();

    //请求数据
    this.setData({
      roomId: options.id
    });
    wx.cloud.database().collection("meetingRoom").doc(options.id).get({
      success: res => {
        let data = res.data;
        let array = this.data.array;
        for(let i = 0; i < array.length; i++){
          if(data.ascription === array[i]){
            this.setData({
              index:i
            })
          }
        }

        this.setData({
          allValue: data,
          mapName: data.address.locateName,
          mapAddress: data.address.locateAddress,
          mapLatitude: data.address.locateAtitude,
          mapLongitude: data.address.locateLongitude,
          roomFilePaths: data.mainImage,
          dayBarOne: data.timeList[0].specDate,
          dayBarTwo: data.timeList[0].specDate,
          dayBarThree: data.timeList[0].specDate,
          dayOne: {
            specDate: currentDate,
            openTime: data.timeList[0].openTime
          },
          dayTwo: {
            specDate: tomorrow,
            openTime: data.timeList[1].openTime
          },
          dayThree: {
            specDate: dayOfTomorrow,
            openTime: data.timeList[2].openTime
          },
        })
      }
    })
  },

  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },

  initValidate() {
    const rules = {
      name: {
        required: true,
        minlength: 1
      },
      address: {
        required: true,
        minlength: 1
      },
      containNum: {
        required: true,
        number: true
      },
    }
    const messages = {
      name: {
        required: '请填写会议室名称',
        minlength: '请输入正确的会议室名称'
      },
      address: {
        required: '请填写会议室地址',
        minlength: '请输入正确的会议室地点名称'
      },
      containNum: {
        required: '请填写可容纳的人数',
        number: "请填写数字"
      },
    }
    this.WxValidate = new WxValidate(rules, messages);
  },

  /* 地图选择地点 */
  getLocation: function () {
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        var name = res.name
        var address = res.address
        var latitude = res.latitude
        var longitude = res.longitude
        _this.setData({
          mapName: name,
          mapAddress: address,
          mapLatitude: latitude,
          mapLongitude: longitude
        })
      },
    })
  },

  /* 选择图片 */
  choose: function () {
    var that = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        });
        let filePath = res.tempFilePaths[0];
        const name = Math.random() * 1000000;
        const cloudPath = name + filePath.match(/\.[^.]+?$/)[0];
        wx.cloud.uploadFile({
          cloudPath, //云存储图片名字
          filePath, //临时路径
          success: res => {
            console.log('[上传图片] 成功：', res)
            that.setData({
              roomFilePaths: res.fileID, //云存储图片路径,可以把这个路径存到集合，要用的时候再取出来
            });
            fileID = res.fileID;
          },
          fail: e => {
            console.error('[上传图片] 失败：', e)
          },
          complete: () => {
            wx.hideLoading()
          }
        });
      }
    })
  },

  /* 切换日期选项 */
  changeDayFlag: function (e) {
    this.setData({
      dayFlag: e.currentTarget.dataset.dayflag
    })
  },

  /* 缓存日期选项 */
  checkboxChange: function (e) {

    //对时间进行变化
    let time = e.detail.value,
      timeObj = {};
    for (let i = 0; i < time.length; i++) {
      let tempObj = {};
      tempObj['state'] = 1;
      tempObj['appointmentId'] = null;
      timeObj[time[i]] = tempObj;
    }

    if (this.data.dayFlag === '0') { //第一天选择项
      //对时间进行变化
      this.setData({
        dayOne: {
          specDate: currentDate,
          openTime: timeObj
        }
      })
    } else if (this.data.dayFlag === '1') {
      this.setData({
        dayTwo: {
          specDate: tomorrow,
          openTime: timeObj
        }
      })
    } else if (this.data.dayFlag === '2') {
      this.setData({
        dayThree: {
          specDate: dayOfTomorrow,
          openTime: timeObj
        }
      })
    }
  },

  //表单提交按钮
  formSubmit: function (e) {
    // 对数据进行验证
    let result = e.detail.value;

    //校验表单
    if (!this.WxValidate.checkForm(result)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false;
    }

    let timeArr = [];
    timeArr.push(this.data.dayOne);
    timeArr.push(this.data.dayTwo);
    timeArr.push(this.data.dayThree);

    result["timeList"] = timeArr;
    result['mainImage'] = fileID || this.data.allValue.mainImage;


    //地点
    let address = result['address'];
    result['address'] = {
      meetingAdress: address,
      locateName: this.data.mapName,
      locateAddress: this.data.mapAddress,
      locateAtitude: this.data.mapLatitude,
      locateLongitude: this.data.mapLongitude
    }

    result["containNum"] = Number(result["containNum"]);

    wx.cloud.database().collection('meetingRoom').doc(this.data.roomId).update({
      data: result,
      success: res => {
        wx.showToast({
          title: '会议室编辑成功！',
          duration: 1000
        })
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/allMeetingRoom/allMeetingRoom'
          })
        }, 1000)


        //给经纬度表单添加信息:编号，经度纬度，详细地址
        let mapMsg = {
          meetingId: res._id,
          longitude: this.data.mapLongitude,
          latitude: this.data.mapLatitude,
          detail: address,
          name: result.name
        }
        console.log(mapMsg)
        wx.cloud.database().collection("meetingMapMsg").add({
          data: mapMsg,
          success: res => {
            console.log(res)
          }
        })
      }
    })
  },

  //表单重置按钮
  formReset: function (e) {
    this.setData({
      allValue: '',
      mapName: '',
      mapAddress: '',
      mapLatitude: '',
      mapLongitude: '',
      roomFilePaths: './../../images/upfile.png',
      dayOne: null,
      dayTwo: null,
      dayThree: null,
    })
  },

  //地区选择
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})